const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
app.use(express.json());
const port = 8000;
//连接池：用于保存连接的用户，广播所有信息
const wsClientsPool = expressWs.getWss('/linkSocket');
let userList = [];//保存用户列表
app.ws('/linkSocket', function (ws, req) {
    // ws.send(JSON.stringify(
    //     {
    //         userName:user,
    //         result:user+'上线',
    //     }
    // ));
    ws.on('message', (msg) => {
        if (msg === 'ping') {
            return ws.send('pong');
        } else {
            const data = JSON.parse(msg)


            let sendData="";
            let userAdd = userList[userList.indexOf(data.chooseUser)];//保存当前用户在 在线用户数组中的位置
            if(data.chooseUser === ""){//为空则代表群聊
                //广播消息（共享给所有人）
                wsClientsPool.clients.forEach((e) => {
                    sendData = {
                        userName: data.user,
                        msg: data.chatContent,
                    }
                    e.send(JSON.stringify(sendData));
                });
            }else if(userAdd != undefined){//如果为true证明该用户是在线的
                //私聊
                console.log("选择给指定人：：",data.chooseUser)
                console.log("当前在线用户：：",userList)
                wsClientsPool.clients.forEach((e) => {
                    console.log("e.userL:::",e.data())
                    console.log("进来了,为true")
                    sendData = {
                        userName: data.user,
                        msg: data.chatContent,
                    }
                    e.send(JSON.stringify(sendData));
                });

            }else{
                ws.send(JSON.stringify({
                    msg:data.chooseUser+"用户不在线！",
                    result:false,
                }))
            }
        }
    });
    ws.on("error", (error) => (
            {
                result: error + "连接异常",
            }
        )
    )
    ws.on('close', function () {
        console.log('客户端下线了');

    });
})
app.post("/user", (req, res) => {
    if (Object.keys(req.body).length === 0) {
        return res.status(500).json({
            success: false,
            msg: "缺少入参"
        });
    }
    if (req.body.userName === "") {
        return res.status(500).json({
            success: false,
            msg: "用户名不能为空"
        });
    }
    userList.push(req.body.userName)//添加用户名
    return res.status(200).json({
        success: true,
        msg: "请求成功"
    });
})

app.listen(port, () => {
    console.log(`在${port}端口启动`);
});